import 'dart:convert';

import 'package:flutter/src/gestures/long_press.dart';
import 'package:flutter/src/gestures/tap.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:situation/app/router/router_name.dart';
import 'package:situation/data/bus/intercom_bus.dart';
import 'package:situation/data/channel/intercom_channel.dart';
import 'package:situation/shared/shared.dart';

import 'state.dart';

class CommunicationIndexController extends GetxController {
  final CommunicationIndexState state = CommunicationIndexState();

  // 去通信录
  void toConcatList() {
    Get.toNamed(RouterName.communicationConcatList);
  }

  void onPress(TapDownDetails details) async {
    bool flag = await UtilPermission.requestMicrophonePermission();
    if (!flag) {
      SmartDialog.showToast("请先允许麦克风权限");
      return;
    }
    IntercomChannel.to.sendMsg({"event": "speak"});
    state.whoTalk = '本机正在讲话';
  }

  void onPressEnd(LongPressEndDetails details) {
    IntercomChannel.to.sendMsg({"event": "stopSpeak"});
    state.whoTalk = '无人讲话';
  }

  void onPressUp(TapUpDetails details) {
    IntercomChannel.to.sendMsg({"event": "stopSpeak"});
    state.whoTalk = '无人讲话';
  }

  void onLongPressDown(LongPressDownDetails details) {
    onPress(TapDownDetails());
  }

  @override
  void onInit() {
    super.onInit();

    state.currentGroupName =
        UtilSp.getString(IntercomChannel.to.GWSD_CURRENT_GROUP_NAME) ?? '';

    IntercomBus.to.getBus().on<IntercomEvent>().listen((event) {
      if (event.event == IntercomChannel.to.GW_PTT_EVENT_SPEAK) {
        // 有人说话
        Map<String, dynamic> json = jsonDecode(event.data);
        if (json.containsKey("name")) {
          state.whoTalk = json["name"] + '正在讲话';
        } else {
          state.whoTalk = '无人讲话';
        }
      }
    });
  }

}
